package top.xiaoazi.futureletterserver.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.xiaoazi.futureletterserver.common.R;
import top.xiaoazi.futureletterserver.exception.ConnectionTimeoutException;
import top.xiaoazi.futureletterserver.exception.UnauthorizedException;

import java.io.IOException;

/**
 * 统一异常处理
 */
@ControllerAdvice
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(UnauthorizedException.class)
    public R handleUnauthorizedException(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        return R.error("未登录或登录过期, 请重新登录!");
    }

    @ExceptionHandler(ConnectionTimeoutException.class)
    public R handleHttpHostConnectException(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        return R.error("服务器连接超时, 请联系管理员.");
    }

    @ExceptionHandler(Throwable.class)
    public R handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        log.error(ex.toString());
        return R.error("服务器错误, 请联系管理员.");
    }

}